package controller;

import model.Log;
import model.LogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-08
 * Time：21:51
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        if (username == null || username.isEmpty()) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名不可为空，请重新输入");
            return;
        }
        String password = req.getParameter("password");
        if (password == null || password.isEmpty()) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("密码不可为空，请重新输入");
            return;
        }
        String confirm = req.getParameter("confirm");
        if (confirm == null || confirm.isEmpty()) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("确认密码不可为空，请重新输入");
            return;
        }
        String gitUrl = req.getParameter("gitUrl");
        if (!password.equals(confirm)) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("密码与确认密码不一致，请重新输入");
            return;
        }
        UserDao userDao = new UserDao();
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setGitUrl(gitUrl);
        userDao.insert(user);
        resp.sendRedirect("login.html");

        //输出日志
        Log log = new Log();
        log.setUserId(user.getUserId());
        log.setAction("该用户注册成功！");
        LogDao logDao = new LogDao();
        logDao.insert(log);
    }
}
